package com.jiandian.controller;

import com.jiandian.crudparams.PageInfo;
import com.jiandian.crudparams.swaggernotes.SysLogNotes;
import com.jiandian.crudparams.dto.AddSysLogDto;
import com.jiandian.crudparams.dto.EditSysLogDto;
import com.jiandian.entity.SysLog;
import com.jiandian.service.SysLogService;
import com.jiandian.util.BaseController;
import com.jiandian.util.BaseResult;
import com.jiandian.util.BeanUtils;
import com.jiandian.util.Constants;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 系统日志
 *
 * @author lik
 * @date 2018/10/26
 */
@Api(value = "SysLog", description = "系统日志")
@RestController
@RequestMapping(value = Constants.CODE_VERSION + "/SysLog")
public class SysLogController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(SysLogController.class);

    @Autowired
    private SysLogService service;

    @ApiOperation(value = "添加", notes = SysLogNotes.ADD_NOTE)
    @ApiImplicitParam(name = "record", value = SysLogNotes.ADD_VALUE, required = true, dataType = "AddSysLogDto")
    @PostMapping("/")
    public BaseResult add(@RequestBody @Validated AddSysLogDto record, BindingResult result){
        logger.info("添加系统日志，参数：\n {}", ReflectionToStringBuilder.toString(record));
        if (result.hasErrors()) {
            FieldError fieldError = result.getFieldError();
            logger.error("添加系统日志参数错误:{}", fieldError.getDefaultMessage());
            return sendResult(Constants.RESPONSE_CODE_400,Constants.RESPONSE_MESSAGE_400, fieldError.getDefaultMessage());
        }
        SysLog bean = new SysLog();
        BeanUtils.copyProperties(record, bean);
        SysLog saveResult = service.add(bean);
        if (saveResult != null) {
            return sendResult(Constants.RESPONSE_CODE_200,Constants.RESPONSE_MESSAGE_200, saveResult);
        }
        return sendResult(Constants.RESPONSE_CODE_400,Constants.RESPONSE_MESSAGE_400, "系统异常");
    }

    @ApiOperation(value = "修改", notes = SysLogNotes.EDIT_NOTE)
    @ApiImplicitParam(name = "record", value = SysLogNotes.EDIT_VALUE, required = true, dataType = "EditSysLogDto")
    @PutMapping("/{id}")
    public BaseResult edit(@PathVariable("id") String id,@RequestBody @Validated EditSysLogDto record, BindingResult result){
        logger.info("修改系统日志，参数：\n {}", ReflectionToStringBuilder.toString(record));
        if (result.hasErrors()) {
            FieldError fieldError = result.getFieldError();
            logger.error("修改系统日志参数错误:{}", fieldError.getDefaultMessage());
            return sendResult(Constants.RESPONSE_CODE_400,Constants.RESPONSE_MESSAGE_400, fieldError.getDefaultMessage());
        }
        SysLog bean = new SysLog();
        BeanUtils.copyProperties(record, bean);
        SysLog updateResult = service.update(bean);
        if (updateResult != null) {
            return sendResult(Constants.RESPONSE_CODE_200,Constants.RESPONSE_MESSAGE_200, updateResult);
        }
        return sendResult(Constants.RESPONSE_CODE_400,Constants.RESPONSE_MESSAGE_400, "系统异常");
    }

    @ApiOperation(value = "列表", notes = SysLogNotes.LIST_NOTE)
    @ApiImplicitParam(name = "pageInfo", value = SysLogNotes.LIST_VALUE, required = true, dataType = "PageInfo")
    @GetMapping("/")
    public BaseResult list(@RequestParam PageInfo pageInfo){
        logger.info("查询系统日志，参数：\n {}", ReflectionToStringBuilder.toString(pageInfo));
        if (pageInfo == null) {
            return sendResult(Constants.RESPONSE_CODE_400,Constants.RESPONSE_MESSAGE_400, "参数pageInfo不存在");
        }
        Map<String, Object> whereMap = pageInfo.getWhereMap();
        if (whereMap == null) {
            return sendResult(Constants.RESPONSE_CODE_400,Constants.RESPONSE_MESSAGE_400, "参数whereMap不存在");
        }
        //if (whereMap.get("projectId") == null) {
        //    return sendResult(Constants.RESPONSE_CODE_400,Constants.RESPONSE_MESSAGE_400, "参数项目projectId不存在");
        //}
        pageInfo.setTotalRecord(service.selectCount(pageInfo));

        if(StringUtils.isEmpty(pageInfo.getOrderColumn())){
            pageInfo.setOrderColumn("id");
        }
        if(StringUtils.isEmpty(pageInfo.getOrderSort())){
            pageInfo.setOrderSort("desc");
        }
        if(pageInfo.getTotalRecord() != 0){
            pageInfo.setResultObject(service.findAll(pageInfo));
        }
        return sendResult(Constants.RESPONSE_CODE_200,Constants.RESPONSE_MESSAGE_200,pageInfo);
    }
    
    @ApiOperation(value = "详情", notes = "系统日志详情")
    @GetMapping("/{id}")
    public BaseResult detail(@PathVariable("id") String id){
        logger.info("查询系统日志，参数：\n id = {}", id);
        if (StringUtils.isBlank(id)) {
            return sendResult(Constants.RESPONSE_CODE_400,Constants.RESPONSE_MESSAGE_400, "参数uuid不存在");
        }
        SysLog record = service.findById(Integer.valueOf(id));
        if (record != null) {
            return sendResult(Constants.RESPONSE_CODE_200,Constants.RESPONSE_MESSAGE_200, record);
        }
        return sendResult(Constants.RESPONSE_CODE_400,Constants.RESPONSE_MESSAGE_400, "不存在");
    }

    @ApiOperation(value = "删除", notes = "根据系统日志id删除")
    @DeleteMapping("/{id}")
    public BaseResult delete(@PathVariable("id") String id){
        logger.info("删除系统日志，参数：\n id = {}", id);
        if (StringUtils.isBlank(id)) {
            return sendResult(Constants.RESPONSE_CODE_400,Constants.RESPONSE_MESSAGE_400, "参数id不存在");
        }
        int deleteResult = service.delete(Integer.valueOf(id));
        if (deleteResult > 0) {
            return sendResult(Constants.RESPONSE_CODE_200,Constants.RESPONSE_MESSAGE_200, "删除成功");
        }
        return sendResult(Constants.RESPONSE_CODE_400,Constants.RESPONSE_MESSAGE_400, "系统异常");
    }

    @ApiOperation(value = "批量删除", notes = "根据系统日志id list批量删除")
    @PostMapping("batchDelete")
    public BaseResult batchDelete(@RequestBody List<Integer> ids){
        logger.info("批量删除系统日志，参数：\n {}", ReflectionToStringBuilder.toString(ids, ToStringStyle.MULTI_LINE_STYLE));
        if (CollectionUtils.isEmpty(ids)) {
            return sendResult(Constants.RESPONSE_CODE_400,Constants.RESPONSE_MESSAGE_400, "参数ids不存在");
        }
        int deleteResult = service.batchDeleteById(ids);
        if (deleteResult > 0) {
            return sendResult(Constants.RESPONSE_CODE_200,Constants.RESPONSE_MESSAGE_200, "删除成功");
        }
        return sendResult(Constants.RESPONSE_CODE_400,Constants.RESPONSE_MESSAGE_400, "系统异常");
    }

}
